from django.shortcuts import render
from django.http import HttpResponse, Http404, JsonResponse
from .models import Info
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.cache import never_cache
import json

# Create your views here.
def info(request):
    info_list = Info.objects.all()
    items = []
    for i in range(len(info_list)):
        data = info_list[i]
        data.index = len(info_list) - i
        data.datetime = data.datetime.strftime('%Y-%m-%d %H:%M:%S')
        item = {
            'pk': data.index,
            'name': data.name,
            'address': data.address,
            'phone': data.phone,
            'datetime': data.datetime
        }
        items.append(item)
    return JsonResponse({'items':items},safe=False)

@csrf_exempt
@never_cache
def infoPost(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        address = request.POST.get('address')
        phone = request.POST.get('phone')

        info = Info(
            name = name,
            address = address,
            phone = phone
        )
        info.save()
        return JsonResponse({'result':'ok'},safe=False)
    elif request.method == 'GET':
        return JsonResponse({'result':'failed'},safe=False)